// pages/labor/list/list.js
const app = getApp()

Page({
  data: {
    laborList: [],
    loading: false,
    hasMore: true,
    page: 1,
    pageSize: 10,
    filterType: 'all', // all 或 labor_type 的 ID
    selectedTypeId: null, // 选中的劳务类型ID
    laborTypes: [], // 劳务类型列表
    searchKeyword: '',
    skill: '',
    location: '',
    workType: '',
    urgent: null
  },

  async onLoad(options) {
    // 检查登录状态
    if (!app.utils.checkLoginStatus()) {
      wx.reLaunch({
        url: '/pages/login/login'
      })
      return
    }

    // 检查是否已选择学校
    if (!app.utils.checkSchoolId()) {
      wx.reLaunch({
        url: '/pages/school-select/school-select'
      })
      return
    }

    // 先加载劳务类型
    await this.loadLaborTypes()
    
    // 检查是否需要自动刷新
    if (options.refresh === 'true') {
      // 延迟一点时间确保页面完全加载后再刷新
      setTimeout(() => {
        this.refreshData()
      }, 300)
    } else {
      this.loadLaborList()
    }
  },

  onShow() {
    // 检查登录状态
    if (!app.utils.checkLoginStatus()) {
      wx.reLaunch({
        url: '/pages/login/login'
      })
      return
    }

    // 检查是否已选择学校
    if (!app.utils.checkSchoolId()) {
      wx.reLaunch({
        url: '/pages/school-select/school-select'
      })
      return
    }

    // 设置tabBar选中状态
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 1
      })
    }
    
    // 如果列表已经加载过，重新刷新数据以获取最新状态
    if (this.data.laborList.length > 0) {
      this.refreshData()
    }
  },

  onPullDownRefresh() {
    this.refreshData()
    wx.stopPullDownRefresh()
  },

  // 刷新数据方法
  refreshData() {
    this.setData({
      page: 1,
      laborList: [],
      hasMore: true
    })
    this.loadLaborList()
  },

  // 加载劳务类型列表
  async loadLaborTypes() {
    try {
      const result = await app.utils.request({
        url: '/labor-types/enabled',
        method: 'GET'
      })
      
      if (result.code === 200) {
        this.setData({
          laborTypes: result.data || []
        })
      } else {
        console.error('获取劳务类型失败:', result.message)
      }
    } catch (error) {
      console.error('获取劳务类型失败:', error)
    }
  },

  onReachBottom() {
    if (this.data.hasMore && !this.data.loading) {
      this.loadLaborList()
    }
  },

  async loadLaborList() {
    if (this.data.loading) return
    
    this.setData({ loading: true })
    
    try {
      const params = {
        page: this.data.page,
        size: this.data.pageSize,
        keyword: this.data.searchKeyword || undefined,
        typeId: this.data.selectedTypeId || undefined,
        skill: this.data.skill || undefined,
        location: this.data.location || undefined,
        workType: this.data.workType || undefined,
        urgent: this.data.urgent
      }
      
      // 移除空值参数
      Object.keys(params).forEach(key => {
        if (params[key] === undefined || params[key] === null || params[key] === '') {
          delete params[key]
        }
      })
      
      const result = await app.utils.request({
        url: '/labor/list',
        method: 'GET',
        data: params
      })
      
      if (result.code === 200) {
        const newList = result.data.records || []
        // 为每个劳务项添加状态文本和发布者类型信息
        const processedList = newList.map(item => ({
          ...item,
          statusText: this.getStatusText(item.status),
          publisherType: item.publisherType,
          publisherTypeText: this.getPublisherTypeText(item.publisherType),
          publisherTypeIcon: this.getPublisherTypeIcon(item.publisherType)
        }))
        
        this.setData({
          laborList: this.data.page === 1 ? processedList : [...this.data.laborList, ...processedList],
          loading: false,
          hasMore: newList.length === this.data.pageSize,
          page: this.data.page + 1
        })
      } else {
        throw new Error(result.message || '获取劳务列表失败')
      }
    } catch (error) {
      console.error('获取劳务列表失败:', error)
      this.setData({ loading: false })
      app.utils.showError(error.message || '获取劳务列表失败')
    }
  },

  onFilterChange(e) {
    const filterType = e.currentTarget.dataset.type
    let selectedTypeId = null
    
    if (filterType !== 'all') {
      selectedTypeId = parseInt(filterType) // filterType 现在是劳务类型的ID
    }
    
    this.setData({
      filterType,
      selectedTypeId,
      page: 1,
      laborList: [],
      hasMore: true
    })
    this.loadLaborList()
  },

  onSearchInput(e) {
    this.setData({
      searchKeyword: e.detail.value
    })
  },

  onSearch() {
    this.setData({
      page: 1,
      laborList: [],
      hasMore: true
    })
    this.loadLaborList()
  },

  navigateToDetail(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/labor/detail/detail?id=${id}`
    })
  },

  navigateToPublish() {
    wx.navigateTo({
      url: '/pages/labor/publish/publish'
    })
  },

  getStatusText(status) {
    const statusMap = {
      'recruiting': '招聘中',
      'filled': '已招满',
      'completed': '已完成',
      'closed': '已关闭'
    }
    return statusMap[status] || '未知状态'
  },

  // 获取发布者类型文本
  getPublisherTypeText(publisherType) {
    const typeMap = {
      'student': '学生发布',
      'merchant': '商户发布'
    }
    return typeMap[publisherType] || ''
  },

  // 获取发布者类型图标
  getPublisherTypeIcon(publisherType) {
    const iconMap = {
      'student': '🎓',
      'merchant': '🏪'
    }
    return iconMap[publisherType] || ''
  }
})
